
<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="申请时间" value="applicationTime" />
          <el-option label="撤销时间" value="cancelTime" />
          <el-option label="驳回时间" value="rebutTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          clearable
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item label="发生机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="handleClear"
        />
      </el-form-item>
      <el-form-item prop="userId" class="merge-item">
        <el-select v-model="userType" style="width: 170px; margin-right: 2px;">
          <el-option label="借入人" value="borrowUserId" />
          <el-option label="借出人" value="loanUserId" />
        </el-select>
        <el-select v-model="userId" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="secondStatus">
        <el-select v-model="query.secondStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="气瓶编号:" prop="recChipIDS">
        <el-input v-model.trim="query.recChipIDS" placeholder="请输入" clearable />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[70104,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <el-button
        v-permission="[70104,2]"
        type="primary"
        icon="el-icon-download"
        :loading="$loadingPlugin.batchExp"
        @click="batchExp"
      >导出</el-button>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import { bottleSecondmentExport, bottleSecondmentList, queryOwnersList, querySecondStatus } from '@/api'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import dayjs from 'dayjs'

  export default {
    name: 'beonLoan',

    props: {
      treeData: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        dateType: 'applicationTime',
        userType: 'borrowUserId',
        userId: '',
        txt: '',
        date: [dayjs(new Date(new Date().setHours(0, 0, 0, 0))).subtract(7, 'day'), new Date(new Date().setHours(0, 0, 0, 0) + 24 * 60 * 60 * 1000 - 1)],
        updateList: [], // 批量操作
        ids: [],
        actionColWidth: 80,
        invalidStr: '',
        ownersList: [],
        searchParams: {},
        query: {
          secondStatus: '',
          recChipIDS: '',
          orgSNNo: ''
        },
        billStatusMap: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'exportDomain'
      ]),
      column: function() {
        const cols = [
          {
            type: 'index'
          },
          {
            prop: 'secondCode',
            label: '借调单号',
            width: 140
          },
          {
            prop: 'orgName',
            label: '发生机构',
            width: 200
          },

          {
            prop: 'secondType',
            label: '借调类型',
            width: 110,
            render: (h, { row }) => <span>{row.secondType === 1 ? '借入' : ''}</span>
          },
          {
            prop: 'borrowUser',
            label: '借入人',
            width: 110
          },
          {
            prop: 'loanUser',
            label: '借出人',
            width: 110
          },
          {
            prop: 'goodsDesc',
            label: '商品数量',
            width: 160
          },
          {
            prop: 'applicationTime',
            label: '申请时间',
            width: 160,
            render: (h, { row }) => row.applicationTime && <span>{ parseTime(row.applicationTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'recChipIDS',
            label: '借调气瓶号',
            width: 110
          },

          {
            prop: 'secondStatus',
            label: '状态',
            width: 110,
            render: (h, { row }) => <span>{ row.secondStatus && formatColumnMap(this.billStatusMap, 'value', row.secondStatus, 'desc') }</span>
          },

          {
            prop: 'cancelTime',
            label: '撤销时间',
            width: 160,
            render: (h, { row }) => row.cancelTime && <span>{ parseTime(row.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'cancelUser',
            label: '撤销人',
            width: 110
          },
          {
            prop: 'rebutTime',
            label: '驳回时间',
            width: 160,
            render: (h, { row }) => row.rebutTime && <span>{ parseTime(row.rebutTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'rebutUser',
            label: '驳回人',
            width: 110
          }
        ]
        return cols
      }
    },
    mounted() {
      this.getQuerySecondStatus()
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          json: { ...this._getQuery(this.query) },
          pageIndex: currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.json[this.dateType + 'start'] = moment(this.date[0]).format()
          query.json[this.dateType + 'End'] = moment(this.date[1]).format()
        }
        query.json[this.userType] = this.userId
        this.searchParams = { ...(query.json),
                              pageIndex: query.currentPage,
                              pageSize: query.pageSize }
        const res = await bottleSecondmentList(query)
        this.tableData.data = res.data.rows
        this.tableData.total = res.data.total
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.handleClear()
        this.getOwnersList(value.orgId)
      },
      handleClear() {
        this.$set(this.query, 'userId', '')
        this.ownersList = []
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const res = await queryOwnersList({
          orgId: org || ''
        })
        this.ownersList = res.data
      },
      async getQuerySecondStatus() {
        const res = await querySecondStatus()
        if (res && res.data) {
          this.billStatusMap = res.data
        }
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 导出
      batchExp() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.pop()
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          const paramInfo = _this._getQuery(params)
          bottleSecondmentExport({
            paramInfo: paramInfo,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-form-item {
  margin-bottom: 10px;
}
.footText {
  position: absolute;
  right: 10px;
  bottom: 5px;
  color: #F56C6C;
}
</style>
